package com.bix.util.blizfiles.dds;

import java.nio.ByteBuffer;

/**
 * This object represents a DDS color block that contains alpha information.
 * 
 *	@author		squid
 *
 *	@version	1.0.0
 */
class DDSColorBlockAlpha extends DDSColorBlock {
	private	int[]	alpha = new int[4];
	
	/**
	 * Instantiate the object from a ByteBuffer.
	 * 
	 * @param bb	The buffer to read the object data from.
	 */
	public DDSColorBlockAlpha (ByteBuffer bb) {
		this.read (bb);
	}
	
	/**
	 * Read the object from a byte buffer. 
	 * 
	 * @param	bb	The buffer to read the object from.
	 */
	public void read (ByteBuffer bb) {
		//
		// Read the alpha information.
		//
		for (int i = 0; i < alpha.length; i++) {
			this.alpha [i] = (bb.getShort () & 0xFFFF);
		}
		
		//
		// Read the color block.
		//
		super.read(bb);
	}
	
	/**
	 * This color type ALWAYS uses the first algorithm as the normal one.  That
	 * is:
	 * 
	 * color[2] = 2/3 color[0] + 1/3 color[1];
	 * color[3] = 1/3 color[0] + 2/3 color[1];
	 * 
	 * @return true, always
	 */
	protected boolean useAlgorithm1 () {
		return true;
	}
	
	public void decode (int destination[], int offset, int width) {
		//
		// This is the array of the only four colors that can exist in this block.
		//
		DDSColor[]	colors = this.getColors();
		
		//
		// Step through the four lines of data to be decoded.  The offset is 
		// incremented by width * 4 because each line contains four values per
		// pixel (red, green, blue, and alpha).
		//
		for (int y = 0; y < 4; y++, offset += width * 4) {
			//
			// Get the pixel lookup table for this row of four pixels.  Each pixel
			// in the lookup table is two bits and points to one of the four possible
			// colors.
			//
			int	lookup = this.getLookup ()[y];
			int	alpha = this.alpha[y];

			//
			// Decode the row.
			//
			for (int x = 0; x < 4; x++ ) {
				//
				// The bits are either 00, 01, 10, or 11 and represent which color to
				// use for the pixel.  This is identical to the DXT1 algorithm.
				//
				DDSColor	color = colors[(lookup & masks[x]) >> shift[x]];
				
				destination[offset + x * 4 + 0] = color.getRed();
				destination[offset + x * 4 + 1] = color.getGreen();
				destination[offset + x * 4 + 2] = color.getBlue();

				//
				// Set the alpha information.
				//
/*				int	value = alpha & 0xF;
				value = value | (value << 4);
				destination[offset + x * 4 + 3] = value;
				alpha >>= 4; */
				
				int temp = x * 4;
				destination[offset + x * 4 + 3] = (alpha & 0xF << temp) >> temp;
			}
		}
	}
}